package com.java1412.web.controller.admin;

import com.google.code.kaptcha.Producer;
import com.java1412.common.utils.ConstantUtil;
import com.java1412.common.utils.R;
import com.java1412.common.utils.ResponseEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author java1412
 * @since 2025-05-20 9:11
 */
@RestController
@RequestMapping(value = "/admin/vc")
// @CrossOrigin    // 允许跨域的注解
@Api(tags = "获取验证码")  // 对控制器的作用的一个说明
public class AdminVerifyCodeController {

    // 定义Producer属性
    @Autowired
    private Producer producer;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping(value = "/vc.jpg")
    @ApiOperation(value = "获取kaptcha验证码")
    public R getVerifyCode() throws Exception {
        // 1.生成验证码
        String text = producer.createText();
        // 2.生成UUID作为key
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        // 3.将验证码设置到redis中
        stringRedisTemplate.opsForValue().set(key, text);
        // 4.设置过期时间
        stringRedisTemplate.expire(key, ConstantUtil.CODE_TIME_OUT, TimeUnit.MINUTES);
        // 5.生成验证码图片
        BufferedImage bi = producer.createImage(text);
        // 6.用输出流将图片输出到前端
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "jpg", fos);
        // 7.返回Base64的编码
        String imageUrl = Base64.getEncoder().encodeToString(fos.toByteArray());
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", key);
        map.put("imageUrl", imageUrl);
        return R.r(ResponseEnum.USER_KAPTCHA_CODE_SUCCESS, map);
    }
}
